<?php

namespace app\api\controller\course;

use app\api\controller\Controller;
use app\api\service\Message;
use app\common\model\Course;
use app\common\model\CourseOrderDetail;
use app\common\model\Fitness as FitnessModel;
use app\common\model\Reservation;
use app\common\model\UserTask;
use think\Cache;
use think\Config;
use think\Db;
use app\common\model\Banner;
use app\api\model\store\Shop as ShopModel;

/**
 * 教练模块
 */
class Coach extends Controller
{
    //教练看谁预约我的
    public function course_reservation()
    {
        $UserData = $this->getUser();   // 用户信息
        if($UserData['is_coach'] != 1){
            return $this->renderError('非法请求!');
        }
        //列表
        $List = Db::name('course_reservation')
            ->alias('c')
            ->join('coach o' ,'c.coach_id = o.coach_id')
            ->join('user u' ,'c.user_id = u.user_id')
            ->join('course r' ,'c.course_id = r.id')
            ->join('course_image i' ,'r.id = i.course_id')
            ->join('upload_file f' ,'i.image_id = f.file_id')
            ->join('store_shop s' ,'c.shop_id = s.shop_id')
            ->group('c.id')
            ->field('c.date,c.time,c.status,c.create_time,u.nickName,u.avatarUrl,r.course_name,r.type,f.file_name,s.shop_name')
            ->where(['o.wxapp_id'=>$UserData['wxapp_id'],'o.user_id'=>$UserData['user_id'],'c.status'=>['in',[0,1,2]]])
            ->order('c.start_time desc')
            ->select()->toArray();
        foreach ($List as $k=>$v){
            if (preg_match('/(uploads)/',$v['avatarUrl'])){
                $List[$k]['avatarUrl'] = base_url().$v['avatarUrl'];
            }
        }
        $reservation = Config::get('reservation');
        return $this->renderSuccess([
            'List' => $List,  // 列表
            'reservation' => $reservation,  // 预约课程状态
        ]);
    }

    //用户看预约记录
    public function user_reservation(){
        $UserData = $this->getUser();   // 用户信息
        //列表
        $List = Db::name('course_reservation')
            ->alias('c')
            ->join('coach o' ,'c.coach_id = o.coach_id')
            ->join('course r' ,'c.course_id = r.id')
            ->join('course_image i' ,'r.id = i.course_id')
            ->join('upload_file f' ,'i.image_id = f.file_id')
            ->join('store_shop s' ,'c.shop_id = s.shop_id')
            ->group('c.id')
            ->field('c.id as reservation_id,c.date,c.time,c.status,c.create_time,o.real_name,r.course_name,r.type,f.file_name,s.shop_name')
            ->where(['c.wxapp_id'=>$UserData['wxapp_id'],'c.user_id'=>$UserData['user_id']])
            ->order('c.start_time desc')
            ->select()
            ->toArray();
        foreach ($List as $key=>$val){
            if($val['file_name'] && $val['file_name'] != ''){
                //返回上传图片路径
                $service = $_SERVER['SERVER_NAME'];//域名
                $List[$key]['file_name'] = base_url()."/uploads/".$val['file_name'];
            }else{
                $List[$key]['file_name'] = '';
            }
        }
        $reservation = Config::get('reservation');
        return $this->renderSuccess([
            'List' => $List,  // 列表
            'reservation' => $reservation,  // 预约课程状态
        ]);
    }

    /**
     * @title 教练排班
     * @author Qian
     * Time: 2023/3/14  11:58
     */
    public function CoachArrange(){
        $user = $this->getUser();
        $data = $this->request->param();
        $choose_day = $data['day'];
//        $date = date('Y-m-d',$choose_day/1000);
        $model = new Reservation();
        $reservation = $model->getAllList(['date'=>$choose_day]);
//        $reservation = $model->getAllList();
        $reservation = $reservation->toArray();
        foreach ($reservation as $k=>$v){
            $reservation[$k]['user']['avatarUrl'] = getAvatarUrl($v['user']['avatarUrl']);
        }
        $reservation_status = [0=>'预约成功',1=>'上课中',2=>'已下课',3=>'取消预约'];
        return $this->renderSuccess(compact('reservation','reservation_status','user'));
    }

    public function test(){
        $str = '2023-03-10';
        echo strtotime("$str + 7 day");
    }

    /**
     * @title 教练取消预约
     * @author Qian
     * Time: 2023/3/14  14:39
     */
    public function CancelReservation(){
        $user = $this->getUser();
        $data = $this->request->param();
        if ($user['is_coach'] != 1){
            return $this->renderError('还不是教练，不可操作');
        }
        $model = new Reservation();
        $reservation = Reservation::detail(['id'=>$data['reservation_id']]);
        if ($reservation->CancelAppoint($user)){
            return $this->renderSuccess([],'取消成功');
        }
        return $this->renderError($reservation->getError() ?: '取消失败');
        if (!$reservation){
            return $this->renderError('预约记录不存在');
        }
        if ($reservation['status'] == 1){
            return $this->renderError('上课中，不可取消');
        }
        if ($reservation['status'] == 2){
            return $this->renderError('已下课，不可取消');
        }
        if ($reservation['status'] == 3){
            return $this->renderError('此预约已取消');
        }
        $now = time();
        if (!($now >= strtotime($reservation['start_time']) && $now <= strtotime($reservation['end_time']))){
            return $this->renderError('上课中');
        }

    }

    /**
     * @title 已经下课的列表
     * @author Qian
     * Time: 2023/3/15  10:26
     */
    public function EndClassList(){
        $reservation = new Reservation();
        $user = $this->getUser();
//        $user['user_id'] = 10702;
        //教练id
        $model = new \app\common\model\store\shop\Coach();
        $coach_id = $model->getCoachId($user['user_id']);
        $list = $reservation->getList(array_merge(['listRows'=>10,'status'=>2,'coach_id'=>$coach_id],$this->request->param()));
        $list = $list->toArray();
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['user']['avatarUrl'] = getAvatarUrl($v['user']['avatarUrl']);
        }
        return $this->renderSuccess(compact('list'));
    }

    /**
     * @title 发布作业
     * @author Qian
     * Time: 2023/3/14  17:03
     */
    public function PublishWork(){
        $data = $this->request->param();
        $user = $this->getUser();
        $reservation = Reservation::detail(['id'=>$data['reservation_id']]);
        if ($this->request->isGet()){
            return $this->renderSuccess($reservation,'');
        }
        if ($user['is_coach'] != 1){
            return $this->renderError('还没有成为教练');
        }
        $coach = \app\store\model\store\shop\Coach::detail(['user_id'=>$user['user_id']]);
        if (!$coach){
            return $this->renderError('还没有成为教练');
        }
//        if ($coach['coach_id'] != $reservation['coach_id']){
//            return $this->renderError('您不是该会员的教练');
//        }
        //请求post
        if ($reservation->PubWork($data)){
            return $this->renderSuccess([],'发布成功');
        }
        return $this->renderError($reservation->getError() ?: '发布失败');
    }

    /**
     * @title 修改作业
     * @author Qian
     * Time: 2023/5/29  10:09
     */
    public function WorkEdit(){
        if (!$this->request->isPost()){
            return $this->renderError('请求错误');
        }
        $data = $this->request->param();
        $user = $this->getUser();
        $reservation = Reservation::detail(['id'=>$data['reservation_id']]);

        if ($user['is_coach'] != 1){
            return $this->renderError('还没有成为教练');
        }
        $coach = \app\store\model\store\shop\Coach::detail(['user_id'=>$user['user_id']]);
        if (!$coach){
            return $this->renderError('还没有成为教练');
        }
//        if ($coach['coach_id'] != $reservation['coach_id']){
//            return $this->renderError('您不是该会员的教练');
//        }
        //请求post
        if ($reservation->EditWork($data)){
            return $this->renderSuccess([],'修改成功');
        }
        return $this->renderError($reservation->getError() ?: '修改失败');
    }

    /**
     * @title 查看作业
     * @author Qian
     * Time: 2023/3/15  14:12
     */
    public function getWork(){
        $data = $this->request->param();
        $task = Reservation::detail(['id'=>$data['reservation_id']]);
        return $this->renderSuccess($task);
    }

    public function helpUser(){
        $param = $this->request->param();
        $help_user = \app\common\model\User::detail(['user_id'=>$param['user_id']]);
        $card = CourseOrderDetail::detail(['course_order_id'=>$param['card_id']],['file']);
        if ($card['user_id'] != $help_user['user_id']){
            return $this->renderError('课程卡和帮约用户不一致');
        }
        return $this->renderSuccess(compact('help_user','card'));
    }

    /**
     * @title 再约一节
     * @author Qian
     * Time: 2023/3/18  11:28
     */
    public function ReservationAgain(){
        $param = $this->request->param();
        if (!isset($param['reservation_id']) || $param['reservation_id'] == ''){
            return $this->renderError('请选择预约课程信息');
        }
        $user = $this->getUser();
        if ($user['is_coach'] != 1){
            return  $this->renderError('还没有成为教练');
        }
        $reservation_id = $param['reservation_id'];
        $info = Reservation::detail(['id'=>$reservation_id]);
        $info = $info->toArray();
        $info['user']['avatarUrl'] = getAvatarUrl($info['user']['avatarUrl']);
        if (!$info){
            return $this->renderError('预约记录不存在');
        }
        if (!$this->request->isPost()){
            return $this->renderSuccess(compact('info'));
        }
        //预约
        if (!$info['coach']){
            return $this->renderError('教练信息不存在');
        }
        if ($info['coach']['user_id'] != $user['user_id']){
            return $this->renderError('此预约的课程不是您的');
        }
        $Course = $info['course'];
        $date = $param['date'];
        $time = $param['time'];
        $appoint_time = date("$date $time");
        if (time() >= strtotime($appoint_time)){
            return $this->renderError('时间已过期');
        }
        if (!$Course){
            return $this->renderError('课程不存在');
        }
        $CourseOrderDetail = $info['orderdetail'];
        if (!$CourseOrderDetail){
            return $this->renderError('课程卡不存在');
        }
        if ($CourseOrderDetail['is_active'] == 0){
            return $this->renderError('课程卡未激活');
        }
        if ($CourseOrderDetail['card_status'] == 0){
            return $this->renderError('课程卡未付款');
        }
        if ($CourseOrderDetail['card_status'] == 4){
            return $this->renderError('课程卡已过期');
        }
        if ($CourseOrderDetail['card_status'] == 5){
            return $this->renderError('课程卡已停用');
        }
        //查看该团课卡次数是否足够
        if($CourseOrderDetail['remain_nums'] == 0){
            return $this->renderError('卡次数已为0');
        }

        if ($Course['type']['value'] == 2){
            //团课 看周几
            $week = date('w',strtotime($appoint_time));
            if ($week == 0){
                $week = 7;
            }
            if (!in_array($week,explode(',',$Course['week']))){
                return $this->renderError('该课程不在可预约的星期内');
            }
            //查看可能是否已满
            //查看该可能已经预约的人数
            $model = new Reservation();
            $appoint_count = $model->getReservationCount(['course_id'=>$Course['id'],'date'=>$date,'status'=>['neq',3]]);

            if($appoint_count  >= $Course['people']){
                return $this->renderError('此课程预约人数已满');
            }
        }else{
            //私教
            $where['course_id'] = $Course['id'];
            $where['date'] = $date;
//            if ($Course['type']['value'] == 1){
//                $where['time'] = $time;
//            }
            $where['time'] = $time;
            $where['coach_id'] = $info['coach_id']; //预约的这个教练
            $where['status'] = ['neq',3];
            $checkReservation = Reservation::detail($where);
            if ($checkReservation){
                return $this->renderError('此时间已被预约');
            }
        }
        Db::startTrans();
        try {
            //保存数据
            $add['course_id'] = $Course['id'];
            $add['user_id']   = $info['user_id'];
            $add['coach_id']  = $info['coach_id'];
            $add['date']      = $date;
            if ($Course['type']['value'] == 1){
                //私教课
                $add['time']  = $time;
                $add['start_time'] = $date." ".$time;
                $add['end_time']   = date("Y-m-d H:i", strtotime( $add['start_time'].' +1 hour'));
            }else{
                //团课
                $add['time'] = $Course['time'];
                $betTime = explode('~',$Course['time']);
                $add['start_time'] = $date." ".$betTime[0];
                $add['end_time']   = $date." ".$betTime[1];
            }
            $add['shop_id']  = $Course['shop_id'];
            $add['wxapp_id']  = $Course['wxapp_id'];
            $add['create_time'] = time();
            $add['course_order_id']  = $info['course_order_id'];
            $add['operator'] = 'coach';
            Db::name('course_reservation')->insert($add);
            //卡更新
            $card_save['remain_nums'] = $CourseOrderDetail['remain_nums'] - 1; //卡的次数减一
            if ($card_save['remain_nums'] == 0){
                $card_save['card_status'] = 3; //已用完
            }
            if ($CourseOrderDetail['nums'] == $CourseOrderDetail['remain_nums']){
                $card_save['card_status']  = 2;//开始生效
                $card_save['start_time']  = time();
                $card_save['expire_time'] =strtotime(date('Y-m-d ',time()+$CourseOrderDetail['days']*24*3600))+86399;//有效期截止
            }
            Db::name('course_order_detail')->where(['course_order_id'=>$info['course_order_id']])->update($card_save);

            Db::commit();
            return $this->renderSuccess([],'预约成功');
        }catch (\Exception $exception){
            Db::rollback();
            return $this->renderError('预约失败');
        }
    }

    /**
     * @title 再约一节(教练选卡选教练选时间)
     * @author Qian
     * Time: 2023/3/18  11:28
     */
    public function ReservationAgainByCard(){
        $param = $this->request->param();

        if (!isset($param['card_id']) || $param['card_id'] == ''){
            return $this->renderError('请选择课程卡');
        }
        $user = $this->getUser();
        if ($user['is_coach'] != 1){
            return  $this->renderError('还没有成为教练');
        }
        $user_id = $param['user_id'];
        $help_user = \app\common\model\User::detail(['user_id'=>$user_id]);
        if (!$user_id){
            return  $this->renderError('帮约用户不存在');
        }
        //课程
        $Course = Course::detail($param['course_id']);
        if (!$Course){
            return $this->renderError('课程不存在');
        }
        $CourseOrderDetail = CourseOrderDetail::detail(['course_order_id'=>$param['card_id']]);
        if (!$CourseOrderDetail){
            return $this->renderError('课程卡不存在');
        }
        if ($CourseOrderDetail['is_active'] == 0){
            return $this->renderError('课程卡未激活');
        }
        if ($CourseOrderDetail['card_status'] == 0){
            return $this->renderError('课程卡未付款');
        }
        if ($CourseOrderDetail['card_status'] == 4){
            return $this->renderError('课程卡已过期');
        }
        if ($CourseOrderDetail['card_status'] == 5){
            return $this->renderError('课程卡已停用');
        }
        //查看该团课卡次数是否足够
        if($CourseOrderDetail['remain_nums'] == 0){
            return $this->renderError('卡次数已为0');
        }
        if ($CourseOrderDetail['user_id'] != $help_user['user_id']){
            return $this->renderError('所选的课程卡和帮约用户不一致');
        }
        if ($CourseOrderDetail['type'] != $Course['type']['value']){
            return $this->renderError('课程卡和所选课程类型不一致');
        }

        $date = $param['date'];

        if ($Course['type']['value'] == 2){
            //团课
            $course_time = explode('~',$Course['time']);
            $course_end = $course_time[1];
            $appoint_time = date("$date $course_end");
            if (time() >= strtotime($appoint_time)){
                return $this->renderError('已经过了课程的结束时间');
            }
            //团课 看周几
            $week = date('w',strtotime($appoint_time));
            if ($week == 0){
                $week = 7;
            }
            if (!in_array($week,explode(',',$Course['week']))){
                return $this->renderError('该课程不在可预约的星期内');
            }
            //查看可能是否已满
            //查看该可能已经预约的人数
            $model = new Reservation();
            $appoint_count = $model->getReservationCount(['course_id'=>$Course['id'],'date'=>$date,'status'=>['neq',3]]);

            if($appoint_count  >= $Course['people']){
                return $this->renderError('此课程预约人数已满');
            }
        }else{
            //私教选择教练
            if (!isset($param['coach_id']) || $param['coach_id'] == ''){
                return $this->renderError('请选择教练');
            }
            $coach = \app\store\model\store\shop\Coach::detail(['coach_id'=>$param['coach_id']]);
            //教练
            if (!$coach){
                return $this->renderError('教练信息不存在');
            }
            $time = $param['time'];
            //私教
            $where['course_id'] = $Course['id'];
            $where['date'] = $date;
//            if ($Course['type']['value'] == 1){
//                $where['time'] = $time;
//            }
            $where['time'] = $time;
            $where['coach_id'] = $param['coach_id']; //预约的这个教练
            $where['status'] = ['neq',3];
            $checkReservation = Reservation::detail($where);
            if ($checkReservation){
                return $this->renderError('此时间已被预约');
            }
        }
        Db::startTrans();
        try {
            //保存数据
            $add['course_id'] = $Course['id'];
            $add['user_id']   = $CourseOrderDetail['user_id'];

            $add['date']      = $date;
            if ($Course['type']['value'] == 1){
                //私教
                $add['coach_id']  = $param['coach_id'];
                $add['time']  = $time; //私教课
                $add['start_time'] = $date." ".$time;
                $add['end_time']   = date("Y-m-d H:i", strtotime( $add['start_time'].' +1 hour'));
                //2023 07 05
                $time_range = $time."~".date('H:i',strtotime( $add['start_time'].' +1 hour'));
            }else{
                //团课
                $add['coach_id']  = $Course['coach_id']; //团课课程选的教练
                $add['time'] = $Course['time']; //团课
                $betTime = explode('~',$Course['time']);
                $add['start_time'] = $date." ".$betTime[0];
                $add['end_time']   = $date." ".$betTime[1];
                //2023 07 05
                $time_range = $betTime[0]."~".$betTime[1];
            }
            $add['shop_id']  = $Course['shop_id'];
            $add['wxapp_id']  = $Course['wxapp_id'];
            $add['create_time'] = time();
            $add['course_order_id']  = $CourseOrderDetail['course_order_id'];
            $add['operator'] = 'coach';
            Db::name('course_reservation')->insert($add);
            //卡更新
            $card_save['remain_nums'] = $CourseOrderDetail['remain_nums'] - 1; //卡的次数减一
            if ($card_save['remain_nums'] == 0){
                $card_save['card_status'] = 3; //已用完
            }
            if ($CourseOrderDetail['nums'] == $CourseOrderDetail['remain_nums']){
                $card_save['card_status']  = 2;//开始生效
                $card_save['start_time']  = time();
                $card_save['expire_time'] =strtotime(date('Y-m-d ',time()+$CourseOrderDetail['days']*24*3600))+86399;//有效期截止
            }
            Db::name('course_order_detail')->where(['course_order_id'=>$CourseOrderDetail['course_order_id']])->update($card_save);

            Db::commit();
            //2023 07 05 发送公众号推送
            $this->GZSend($help_user,$add['coach_id'],$add['date']." ".$time_range,$Course['course_name']);
            return $this->renderSuccess([],'预约成功');
        }catch (\Exception $exception){
            Db::rollback();
            return $this->renderError('预约失败');
        }
    }

    public function getCourseTime(){
        $now = strtotime(date('Y-m-d'));
        $current = time();
        $param = $this->request->param();
        $date = $param['date'];
        $reservation_id = $param['reservation_id'];
        $WeekRange = []; //两周内的时间
        for ($i=0;$i<14;$i++){
            $WeekRange[$i] = date('Y-m-d',$now+$i*86400);
        }
        if (!in_array($date,$WeekRange)){
            return $this->renderError('只能预约两周内的课程');
        }
        $t1 = strtotime("$date 08:00");
        $t2 = strtotime("$date 21:00");
        $timeslots = array();
        while ($t1 < $t2) {
            $t1 = $t1 + 3600;
            $timeslots[] = $t1;
        }
        $betTime = array();
        foreach ( $timeslots as $slot ) {
            $betTime[] = date("H:i",$slot);
        }
        //预约记录
        $info = Reservation::detail(['id'=>$reservation_id]);
        $reData = [];
        //遍历时间区间是否能预约
        foreach ($betTime as $k=>$v){
            $reData[$k]['time'] = $v;
            $start = date("$date $v"); //开课时间点
            $where['course_id'] = $info['course_id'];//同课程
            $where['coach_id'] = $info['coach_id']; //同教练
            $where['date'] = $param['date'];  //同时间
            $where['time'] = $v;  //同时间
            $where['shop_id'] = $info['shop_id'];  //同门店
            $user_reservation = Reservation::detail($where);
            if ($user_reservation){
                //已经被预约
                if ($user_reservation['user_id'] == $info['user_id']){
                    //被他本人预约
                    $reData[$k]['type'] = 1;//已被预约
                    $reData[$k]['tips'] = '已被该学员预约';
                }else{
                    //被其他人预约
                    $reData[$k]['type'] = 1;//已被预约
                    $reData[$k]['tips'] = '已被其他人预约';
                }
            }elseif ($current >= strtotime($start)){
                $reData[$k]['type'] = -1;//已过期
                $reData[$k]['tips'] = '时间已过期';
            }else{
                //可以预约
                $reData[$k]['type'] = 0;//可以预约
                $reData[$k]['tips'] = '可以预约';
//                if ($current >= (strtotime($start) - 3*60*60) && $current <= strtotime($start)){
//                    $reData[$k]['type'] = -2;//3小时内不可预约
//                    $reData[$k]['tips'] = '开课前3小时内不可预约';
//                }else{
//                    $reData[$k]['type'] = 0;//可以预约
//                    $reData[$k]['tips'] = '可以预约';
//                }
            }
        }
        return  $this->renderSuccess([
            'data'=> $reData, //时间数据
        ]);
    }

    public function getCourseTimeByCard(){
        $now = strtotime(date('Y-m-d'));
        $current = time();
        $param = $this->request->param();
        $date = $param['date'];
//        $reservation_id = $param['reservation_id'];
        $WeekRange = []; //两周内的时间
        for ($i=0;$i<14;$i++){
            $WeekRange[$i] = date('Y-m-d',$now+$i*86400);
        }
        if (!in_array($date,$WeekRange)){
            return $this->renderError('只能预约两周内的课程');
        }
        $course = Course::detail($param['course_id']);
        if (!$course){
            return $this->renderError('所选课程不存在');
        }
        $coach = \app\store\model\store\shop\Coach::detail(['coach_id'=>$param['coach_id']]);
        if (!$coach){
            return $this->renderError('教练不存在');
        }
        $t1 = strtotime("$date 08:00");
        $t2 = strtotime("$date 21:00");
        $timeslots = array();
        while ($t1 < $t2) {
            $t1 = $t1 + 3600;
            $timeslots[] = $t1;
        }
        $betTime = array();
        foreach ( $timeslots as $slot ) {
            $betTime[] = date("H:i",$slot);
        }
//        $info = Reservation::detail(['id'=>$reservation_id]);
        $reData = [];
        //遍历时间区间是否能预约
        foreach ($betTime as $k=>$v){
            $reData[$k]['time'] = $v;
            $start = date("$date $v"); //开课时间点
            $where['course_id'] = $param['course_id'];//同课程
            $where['coach_id'] = $param['coach_id']; //同教练
            $where['date'] = $param['date'];  //同时间
            $where['time'] = $v;  //同时间
            $where['shop_id'] = $coach['shop_id'];  //同门店
            $user_reservation = Reservation::detail($where);
            if ($user_reservation){
                //已经被预约
                if ($user_reservation['user_id'] == $param['user_id']){
                    //被他本人预约
                    $reData[$k]['type'] = 1;//已被预约
                    $reData[$k]['tips'] = '已被该学员预约';
                }else{
                    //被其他人预约
                    $reData[$k]['type'] = 1;//已被预约
                    $reData[$k]['tips'] = '已被其他人预约';
                }
            }elseif ($current >= strtotime($start)){
                $reData[$k]['type'] = -1;//已过期
                $reData[$k]['tips'] = '时间已过期';
            }else{
                //可以预约
                $reData[$k]['type'] = 0;//可以预约
                $reData[$k]['tips'] = '可以预约';
//                if ($current >= (strtotime($start) - 3*60*60) && $current <= strtotime($start)){
//                    $reData[$k]['type'] = -2;//3小时内不可预约
//                    $reData[$k]['tips'] = '开课前3小时内不可预约';
//                }else{
//                    $reData[$k]['type'] = 0;//可以预约
//                    $reData[$k]['tips'] = '可以预约';
//                }
            }
        }
        return  $this->renderSuccess([
            'data'=> $reData, //时间数据
            'info'=>$coach,
            'course'=>$course,
        ]);
    }
    /**
     * @title 我的会员（所有的）
     * @author Qian
     * Time: 2023/4/23  9:02
     */
    public function UserList(){
        $user = $this->getUser();
        if ($user['is_coach'] != 1 && $user['user_id'] != 10005){
            return $this->renderError('还不是教练哦');
        }
//        if ($user['user_id'] == 10005){
//            $user = \app\api\model\User::detail(['user_id'=>10702]);
//        }
        $coach = \app\common\model\Coach::get(['user_id'=>$user['user_id']]);
        $model = new \app\api\model\User();
        $list = $model->getList($this->request->param(),$coach['coach_id']);

        return $this->renderSuccess(compact('list'));
    }

    public function UserDetail($user_id){
        $model = new \app\api\model\User();
        $detail = $model->userDetail($user_id);
        //2023 05 19 上课总次数
        $reservationModel = new Reservation();
        $reservation_count = $reservationModel->getReservationCount(['user_id'=>$user_id,'status'=>2]);
        return $this->renderSuccess(compact('detail','reservation_count'));
    }

    public function UserFitness($user_id){
        $model = new FitnessModel();
        $ObjList = $model->getList(array_merge(['user_id'=>$user_id],$this->request->param()));
        $list = $ObjList->toArray()['data'];
        foreach ($list as $k=>$v){
            $list[$k]['data'] = json_decode($v['data'],true);
        }
        return $this->renderSuccess(compact('list'));
    }

    /**
     * @title 查看我的会员的基本资料
     * @param $user_id
     * @author Qian
     * Time: 2023/5/19  13:49
     */
    public function getHelpUser($user_id){
        $user = \app\api\model\User::detail(['user_id'=>$user_id]);
        return $this->renderSuccess(compact('user'));
    }

    /**
     * @title 查看会员的上课记录
     * @author Qian
     * Time: 2023/5/19  13:53
     */
    public function getUserReservation(){
        $param = $this->request->param();
        $reservationModel = new Reservation();
        $list = $reservationModel->getList(array_merge([
            'listRows'=>15
        ],$param),['start_time'=>'desc']);
        $status = [
            0=>[
                'color'=>'#D8571D',
                'name'=>'待上课'
            ],
            1=>[
                'color'=>'green',
                'name'=>'上课中'
            ],
            2=>[
                'color'=>'#D8571D',
                'name'=>'已下课'
            ],
            3=>[
                'color'=>'#999',
                'name'=>'取消预约'
            ],
        ];

        return $this->renderSuccess(compact('list','status'));
    }


    /**
     * @title 教练添加训练计划表
     * @author Qian
     * Time: 2023/5/24  13:58
     */
    public function addFitness(){
        if ($this->request->isPost()){
            $data = $this->request->param();
            $fit_data = json_decode(htmlspecialchars_decode($data['data']),true);
            $user = $this->getUser();
            if ($user['is_coach'] != 1 && $user['user_id'] != 10005){
                return $this->renderError('还不是教练');
            }
            $coach = \app\store\model\store\shop\Coach::detail(['user_id'=>$user['user_id']]);
            if (!$coach && $user['user_id'] != 10005){
                return $this->renderError('还不是教练！');
            }
            if ($data['title'] == ''){
                return $this->renderError('请输入标题');
            }
            if ($data['date'] == ''){
                return $this->renderError('请输入上课时间');
            }
            if (!isset($fit_data['reshen'])){
                return $this->renderError('请填写热身数据');
            }
            if (!isset($fit_data['train'])){
                return $this->renderError('请填写训练数据');
            }
            $reshen_effect = array_filter($fit_data['reshen'],function ($item){
                return $item['dong'] != '' && $item['ci'] != '';
            });
            if (count($reshen_effect) == 0){
                return $this->renderError('至少填写一组热身数据');
            }
            $train_effect = array_filter($fit_data['train'],function ($item){
                return $item['move'] != '' && $item['dong_ci'] != '' && $item['finish'] != '';
            });
            if (count($train_effect) == 0){
                return $this->renderError('至少填写一组训练数据');
            }
//            $example = [
//                'user_id'=>'',
//                'title'=>'',
//                'date'=>'',
//                'data'=>[
//                    'reshen'=>[
//                        ['dong'=>'','ci'=>''],
//                        ['dong'=>'','ci'=>''],
//                        ['dong'=>'','ci'=>''],
//                    ],
//                    'train_object'=>'',
//                    'train'=>[
//                        ['move'=>'','dong_ci'=>'','finish'=>''],
//                        ['move'=>'','dong_ci'=>'','finish'=>''],
//                        ['move'=>'','dong_ci'=>'','finish'=>''],
//                    ],
//                    'sum_up'=>'',
//                ]
//            ];
            $add['title'] = $data['title'];
            $add['date'] = $data['date'];
            $add['type'] = 6;//训练计划新版
//            $add['data'] = json_encode($data['data'],true);
            $add['data'] = $data['data'];
            $add['wxapp_id'] = $user['wxapp_id'];
            $add['user_id'] = $data['user_id'];
            $add['coach_id'] = $coach['coach_id'];
            $add['shop_id'] = $coach['shop_id'];
            $model = new FitnessModel();
            if ($model->allowField(true)->save($add)){
                return $this->renderSuccess([],'添加成功');
            }else{
                return $this->renderError('添加失败');
            }

        }
    }

    /**
     * @title 上课通知
     * @author Qian
     * Time: 2023/7/6  16:40
     */
    public function lesson(){
        $where['start_time'] = [['EGT',date('Y-m-d H:i:s')],['ELT',date('Y-m-d H:i:s',time()+1*60*60)],'and'];
        $list = Reservation::where($where)->order('start_time asc')->select();
        dump($list->toArray());die;
        foreach ($list as $k=>$v){
            //检查是否已经发过了
            $search['coach_id'] = $v['coach_id'];
            $search['course_id'] = $v['course_id'];
            $search['start_time'] = $v['start_time'];
            $check = Db::name('gz_push')->where($search)->find();
            if (!$check){
                //获取教练的gzopenid
                $user_id = Db::name('coach')->where('coach_id',$v['coach_id'])->value('user_id');
                $coach_user = Db::name('user')->where('user_id',$user_id)->find();
                if ($coach_user && $coach_user['gz_open_id'] != ''){
                    //推送
                    $course = Db::name('course')->find($v['course_id']);
                    $this->GZLesson($coach_user,$v['start_time'],$course['course_name']);
                    //插入表
                    $add['coach_id'] = $v['coach_id'];
                    $add['course_id'] = $v['course_id'];
                    $add['start_time'] = $v['start_time'];
                    $add['wxapp_id'] = $v['wxapp_id'];
                    $add['create_time'] = time();
                    Db::name('gz_push')->insert($add);
                }

            }
        }
    }

    public function testlesson(){
        $coach_user['gz_open_id'] = 'o1vlg6a8NO7WiA2C6sYqB3pGqCLA';
        $test = Reservation::find(25);
        $this->GZLesson($coach_user,$test['start_time'],'测试课程');
    }

    public function GZSend($user,$coach_id,$reservation_time,$course_name){
        $params = [];
        $coach = \app\store\model\store\shop\Coach::detail(['coach_id'=>$coach_id]);
        if ($coach['user']['gz_open_id'] != ''){
            //获取到了公众号openid
            $params['gz_open_id'] = $coach['user']['gz_open_id'];
            $params['nickName'] = $user['nickName'];
            $params['coachName'] = $coach['real_name'];
            $params['reservation_time'] = $reservation_time;
            $params['remark'] = '预约课程：'.$course_name;
            $message = new Message();
            $message->send($params);
        }
    }

    public function GZLesson($coach_user,$start_time,$course_name){
        $params['gz_open_id'] = $coach_user['gz_open_id'];
        $params['course_name'] = $course_name;
        $params['start_time'] = $start_time;
        $message = new Message();
        $message->lesson($params);
    }
}